package com.ky.manage.fragment;

import android.view.View;
import android.widget.ImageView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ky.manage.BaseApplication;
import com.ky.manage.R;
import com.ky.manage.activity.outdoor.OutdoorDetailActivity;
import com.ky.manage.adapter.OutdoorModifyTabAdapter;
import com.ky.manage.base.BaseActivity;
import com.ky.manage.base.BaseFragment;
import com.ky.manage.constant.OverallData;
import com.ky.manage.model.LoginUserInfo;
import com.ky.manage.model.response.OutdoorMendListResp;
import com.ky.manage.ui.RecycleViewDivider;
import com.ky.manage.utils.ScreenUtils;
import com.ky.manage.utils.ToastUtils;
import com.ky.manage.utils.ZyUtils;
import com.ky.manage.utils.http.AsyncHttpUtils;
import com.ky.manage.utils.http.BusinessHttpReqUtils;
import com.ky.manage.utils.log.ObjectUtil;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;

import java.util.ArrayList;

import cz.msebera.android.httpclient.Header;

import static com.ky.manage.utils.http.BusinessHttpReqUtils.SERVICE_DOMAIN;

/**
 * 户外整改TAB页
 */
public class OutdoorModifyTabFragment extends BaseFragment {
    private OutdoorModifyTabAdapter mModifyTabAdapter;
    private int mCurPageIndex = OverallData.DEFAULT_REQ_PAGE_NUM;
    private int mCurListCnt;
    private RefreshLayout refreshLayout;
    private ImageView mToTopIv;
    private RecyclerView recyclerView;
    private boolean mIsReqListData = false;
    /**
     * 状态（0正常， 1待整改， 2已整改）
     */
    private String mStatus;

    public OutdoorModifyTabFragment() {
    }

    /**
     * 隐患（故障）等级： 1 是一级  2是二级  0  正常
     * "":全部
     * 0：正常
     * 1：一级
     * 2：二级
     */
    public OutdoorModifyTabFragment(String status) {
        this.mStatus = status;
    }

    @Override
    protected int layoutId() {
        return R.layout.layout_outdoor_modify_tab_fragment;
    }

    @Override
    protected void initView(View rootView) {
        mToTopIv = findView(R.id.to_top_iv, v -> {
            //置顶
            recyclerView.smoothScrollToPosition(0);
            mToTopIv.setVisibility(View.GONE);
        });
        recyclerView = findView(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.VERTICAL,
                ScreenUtils.dp2px(10), mContext.getColor(R.color.gray_light)));
        mModifyTabAdapter = new OutdoorModifyTabAdapter(mContext,
                R.layout.layout_outdoor_modify_item, new ArrayList<>());
        mModifyTabAdapter.setOnItemClickListener((adapter , view , position) -> {
            //条目点击
            OutdoorDetailActivity.toDetailPage((BaseActivity)getActivity(), mModifyTabAdapter.getItem(position));
        });
        recyclerView.setAdapter(mModifyTabAdapter);
        mModifyTabAdapter.notifyDataSetChanged();

        refreshLayout = findView(R.id.refreshLayout);
        refreshLayout.setRefreshHeader(new ClassicsHeader(mContext));
        refreshLayout.setRefreshFooter(new ClassicsFooter(mContext));
        refreshLayout.autoRefresh();
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            if (mIsReqListData) {
                return;
            }
            mCurPageIndex = OverallData.DEFAULT_REQ_PAGE_NUM;
            requestOutdoorMendListData();
        });
        refreshLayout.setOnLoadMoreListener(refreshlayout -> {
            if (mIsReqListData) {
                return;
            }
            mToTopIv.setVisibility(mCurPageIndex > 2 ? View.VISIBLE : View.GONE);
            requestOutdoorMendListData();
        });
    }

    /**
     * 无数据界面
     */
    private void showEmptyView() {
        mModifyTabAdapter.getData().clear();
        mModifyTabAdapter.setEmptyView(R.layout.layout_empty_data);
        mModifyTabAdapter.notifyDataSetChanged();
    }

    /**
     * 获取户外整改记录列表
     */
    private void requestOutdoorMendListData() {
        LoginUserInfo loginUserInfo = BaseApplication.getLoginUserInfo();
        if (null == loginUserInfo || !ZyUtils.getInstance().isNetConnected()) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
            return;
        }
        mIsReqListData = true;
        RequestParams httpParams = new RequestParams();
        httpParams.put("pageNum", mCurPageIndex);
        httpParams.put("pageSize", OverallData.REQ_PAGE_CNT);
        if (null != mStatus && !"".equals(mStatus)) {
            httpParams.put("status", mStatus);
        } else {
            //请求全部
        }
        ZyUtils.getInstance().insertLog("requestOutdoorMendListData", "req mCurPageIndex = "
                + mCurPageIndex + ", httpParams = " + ObjectUtil.objectToString(httpParams));
        AsyncHttpUtils.getInstance().get(SERVICE_DOMAIN + "/appApi/getOutdoorMendList", httpParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                ZyUtils.getInstance().insertLog("requestOutdoorMendListData", "onFailure statusCode = " +
                        statusCode + ", errorResponse = "+ responseString
                        + ", throwable = " + throwable.getMessage());
                ToastUtils.showRoundRectToast("获取列表数据失败：" + throwable.getMessage());
                if (mCurPageIndex == OverallData.DEFAULT_REQ_PAGE_NUM) {
                    refreshLayout.finishRefresh();
                } else {
                    refreshLayout.finishLoadMore();
                }
                mIsReqListData = false;
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                OutdoorMendListResp outdoorMendListResp = BusinessHttpReqUtils.getInstance().parseJsonObj
                        (responseString, OutdoorMendListResp.class);
                if (null != outdoorMendListResp) {
                    if (outdoorMendListResp.code == 200) {
                        int curPageDataCnt = null == outdoorMendListResp.rows ? 0 : outdoorMendListResp.rows.size();
                        ZyUtils.getInstance().insertLog("requestOutdoorMendListData", "onSuccess mCurPageIndex = "
                                + mCurPageIndex + ", curPageDataCnt = " + curPageDataCnt);
                        if (mCurPageIndex == OverallData.DEFAULT_REQ_PAGE_NUM) {
                            mModifyTabAdapter.setList(curPageDataCnt == 0 ? new ArrayList<>() : outdoorMendListResp.rows);
                            mCurListCnt = curPageDataCnt;
                            if (mCurListCnt == 0 || mCurListCnt >= outdoorMendListResp.total) {
                                refreshLayout.finishRefreshWithNoMoreData();
                                if (mCurListCnt == 0 ) {
                                    showEmptyView();
                                }
                            } else {
                                refreshLayout.finishRefresh();
                                ++mCurPageIndex;
                            }
                        } else {
                            if (curPageDataCnt > 0 ) {
                                mModifyTabAdapter.addData(outdoorMendListResp.rows);
                            }
                            mCurListCnt += curPageDataCnt;
                            if (curPageDataCnt == 0 || mCurListCnt >= outdoorMendListResp.total) {
                                refreshLayout.finishLoadMoreWithNoMoreData();
                                ZyUtils.getInstance().insertLog("requestOutdoorMendListData","没有更多数据");
                            } else {
                                refreshLayout.finishLoadMore();
                                ++mCurPageIndex;
                                ZyUtils.getInstance().insertLog("requestOutdoorMendListData","有更多数据");
                            }
                        }
                    } else if (outdoorMendListResp.code == 401){
                        //登陆失效，需重新登陆
                        BusinessHttpReqUtils.getInstance().autoPwdLogin(mContext);
                    } else {
                        ToastUtils.showRoundRectToast("获取列表数据失败: " + outdoorMendListResp.msg);
                    }
                } else {
                    ToastUtils.showRoundRectToast("获取列表数据失败");
                }
                mIsReqListData = false;
            }
        });
    }

    @Override
    protected void initData() {

    }
}
